﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;

namespace SelectServer
{
    public class YJYSocket
    {
        bool m_Destroy;
        EventDispath m_ClientMsg;

        /// <summary>
        /// 类的构造函数
        /// </summary>
        public YJYSocket()
        {
            Start();
        }

        /// <summary>
        /// 析构函数，用于销毁资源
        /// </summary>
        ~ YJYSocket()
        {
            OnDestroy();
        }

        void Start()
        {
            m_Destroy = false;
            //服务器IP地址
            SelectServer.Server.Start();
            m_ClientMsg = new EventDispath();
            m_ClientMsg.RegistEvent(123, Action_123);
        }

        // Update is called once per frame
        void Update()
        {
            if (!m_Destroy)
            {
                SelectServer.ClientMsgUnPack clientMsg = null;
                SelectServer.Server.GetMsg(ref clientMsg);
                if (null != clientMsg)
                {
                    Debug.Print("Msg:" + clientMsg.GetMsgID() + " from: " + clientMsg.GetUserID());

                    EventNode mNode = new EventNode();
                    mNode.m_EventID = clientMsg.GetMsgID(); ;
                    mNode.msg = clientMsg;
                    m_ClientMsg.AddEvent(mNode);
                }

                m_ClientMsg.Proccess();
            }
        }

        void OnDestroy()
        {
            m_Destroy = true;
            SelectServer.Server.Destroy();
        }

        void Action_123(SelectServer.ClientMsgUnPack msg)
        {
            long userID = msg.GetUserID();
            ushort accountLen = msg.ReadUShort();
            string account = msg.ReadString(accountLen);
            ushort passLen = msg.ReadUShort();
            string pass = msg.ReadString(passLen);

            Debug.Print("Action_123 account: " + account + " pass word: " + pass + " from user: " + userID);

            SelectServer.MsgPack sendMsg = new SelectServer.MsgPack();
            sendMsg.SetHead(123);
            string strAccount = "test account";
            sendMsg.Pack16bit((ushort)strAccount.Length);
            sendMsg.PackString(strAccount, (ushort)strAccount.Length);
            string strPass = "test pass word";
            sendMsg.Pack16bit((ushort)strPass.Length);
            sendMsg.PackString(strPass, (ushort)strPass.Length);
            sendMsg.PackEnd();
            SelectServer.Server.SendTo(ref sendMsg, msg.GetUserID());
        }
    }
}
